package com.wyc.serviceMap.remote;

import com.wyc.internalCommon.constant.AmapConfigConstant;
import com.wyc.internalCommon.response.TerminalResponse;
import com.wyc.internalCommon.response.TrackResponse;
import com.wyc.internalCommon.result.ApiResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 轨迹api
 */

@Service
public class TrackClient {

    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 添加终端
     * @param tid
     * @return
     */
    public ApiResult add(String tid){
        // 拼接路径url
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstant.TRACK_ADD_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key="+amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid="+amapSid);
        urlBuilder.append("&");
        urlBuilder.append("tid="+tid);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");

        String trname = "";
        if (data.has("trname")){
            trname = data.getString("trname");
        }

        String trid = data.getString("trid");
        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        trackResponse.setTrname(trname);

        return ApiResult.success(trackResponse);

    }

}
